// pages/index/index.js
const app = getApp()
import {
  request
} from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [],
    activeTab: 1,
    tabSwiperHeight: 400,
    showQR: false,
    scrollTop: false,
    userInfo: null,
    banner: null,
    page: 1,
    is_new: 2,
    canIUseGetUserProfile: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    // console.log(options.scene, 'options')
    app.globalData.pid = options.scene
    console.log(app.globalData.pid)
    app.globalData.userInfo && this.setData({
      userInfo: app.globalData.userInfo,
    })
    app.globalData.is_new && this.setData({
      is_new: app.globalData.is_new
    })
    // 请求登录并请求首页数据
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // console.log(res)
        request('/api/common/login', '', 'get', {
          code: res.code
        }).then(res => {
          console.log(res, '登录返回');
          app.globalData.token = res.token
          app.globalData.is_new = res.is_new
          // wx.setStorageSync('token', res.token)
          // wx.setStorageSync('is_new', res.is_new)
          if (res.is_new !== 0) {
            request('/api/user/info', res.token).then(res => {
              console.log(res, "config");
              app.globalData.userInfo = res.data
            })
          }
          if (res.is_new === 2 && app.globalData.pid) {
            request('/api/user/bindingUser?pid=' + app.globalData.pid, app.globalData.token, 'put', ).then(res => {})
          }
          // console.log(res, 'data')
          // console.log(res, '登录返回');
          const {
            is_new
          } = res
          this.setData({
            is_new
          })
          this.loadData().then(async res => {
            let {
              banner,
              cate
            } = res.data
            if (!banner || banner.length <= 0) {
              banner = [{
                image: ['../../public/img/home_banner@2x.png']
              }]
            }
            this.setData({
              banner
            })
            console.log(res.data, 1)
            const requestArr = cate instanceof Array && cate.map((item, index) => {
              return this.product(item.id)
            })
            await Promise.all(requestArr).then(items => {
              console.log(items)
              let tabs = cate instanceof Array && cate.map((item, index) => {
                item.list = items[index].data
                item.page = 1
                return item
              })
              // tabs = tabs.concat(tabs)
              this.setData({
                tabs
              })
              this.setData({
                activeTab: 0
              })

            })
          })
        }).catch(err => {
          console.log(err, '登录错误');
        })
      }
    })
  },
  // 首页数据
  loadData: () => {
    return request('/api/index/home', app.globalData.token).then(res => res)
  },
  // 产品数据
  product: function (activeTab, page, size) {
    const data = {
      page: page || 1,
      size: size || 8,
      cate: activeTab || 0
    }
    return new Promise((resolve, reject) => {
      request('/api/product/info', app.globalData.token, 'post', data).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 新版获取用户信息
  getUserInfoProfile(e) {
    wx.getUserProfile({
      desc: '用于体验完善的服务流程',
      success: res => {
        // 获取授权得到的
        const {
          encryptedData,
          iv,
          userInfo
        } = res
        console.log(res,1234213421452)
        // app.globalData.login().then(res => {
        request('/api/user/info', app.globalData.token, 'put', {
          encryptedData,
          iv
        }).then(res => {
          console.log(res, '授权用户信息返回信息++++++++')
          if (res.code === 200) {
            this.setData({
              is_new: 2,
              userInfo: {
                ...app.globalData.userInfo,
                ...userInfo,
              }
            })
            app.globalData.userInfo = {
              ...app.globalData.userInfo,
              ...userInfo
            }
            app.globalData.is_new = 2
            app.globalData.token = res.data
            // wx.setStorageSync('token', res.data)
            if (app.globalData.pid) {
              request('/api/user/bindingUser?pid=' + app.globalData.pid, app.globalData.token, 'put', ).then(res => {})
            }
          }
        })
        // })
      }
    })
  },
  // 授权用户信息
  getUserInfo(e) {
    if (e.detail.errMsg === "getUserInfo:fail auth deny") return
    console.log(e, '用户信息')
    // 获取授权得到的
    const {
      encryptedData,
      iv,
      userInfo
    } = e.detail

    // app.globalData.login().then(res => {
    request('/api/user/info', app.globalData.token, 'put', {
      encryptedData,
      iv
    }).then(res => {
      console.log(res, '授权用户信息返回信息++++++++')
      if (res.code === 200) {
        this.setData({
          is_new: 2,
          userInfo: {
            ...app.globalData.userInfo,
            ...userInfo,
          }
        })
        app.globalData.userInfo = {
          ...app.globalData.userInfo,
          ...userInfo
        }
        app.globalData.is_new = 2
        app.globalData.token = res.data
        // wx.setStorageSync('token', res.data)
        if (app.globalData.pid) {
          request('/api/user/bindingUser?pid=' + app.globalData.pid, app.globalData.token, 'put', ).then(res => {})
        }
      }
    })
    // })

  },
  // 授权手机号码
  getPhoneNumber(e) {
    console.log(e);
    if (e.detail.errMsg === "getPhoneNumber:fail user deny") return
    // 获取授权得到的
    const {
      encryptedData,
      iv
    } = e.detail

    // app.globalData.login().then(res => {
    request('/api/user/phone', app.globalData.token, 'post', {
      encryptedData,
      iv
    }).then(res => {
      console.log(res, '授权手机号返回信息++++++++')
      if (res.code === 200) {
        this.setData({
          is_new: 1,
          userInfo: {
            ...this.data.userInfo,
            phone: res.data.phone
          }
        })
        app.globalData.userInfo = {
          ...this.data.userInfo,
          phone: res.data.phone
        }
        app.globalData.is_new = 1
      }
    })
    // })

  },
  tabsSwiperHeight() {
    // tab 组件内的swiper高度自适应问题
    let index = this.data.activeTab;
    let queryDom = wx.createSelectorQuery()
    queryDom.select('.tab-content-' + index).boundingClientRect().exec(rect => {
      this.setData({
        tabSwiperHeight: rect[0].height
      })
    })
    console.log(this.data.tabSwiperHeight, 'tabSwiperHeight')
  },
  onChange(e) {
    const index = e.detail.index
    console.log(e, 'e');
    const tabs = this.data.tabs
    tabs[this.data.activeTab].page = this.data.page

    this.setData({
      activeTab: index,
      tabs,
      page: tabs[index].page
    })
    this.tabsSwiperHeight();

  },
  // 课程跳转
  handleClick(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/course-detail/index?id=' + id,
    })
  },
  // 联系客服
  talkus() {
    this.setData({
      showQR: !this.data.showQR
    })
    // console.log(this.data.showQR)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      userInfo: app.globalData.userInfo,
      is_new: app.globalData.is_new,
    })
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        console.log(res, 444)
        app.globalData.mainSwitch = res.subscriptionsSetting.mainSwitch
      }
    })
    app.globalData.userInfo && wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // console.log(res)
        request('/api/common/login', '', 'get', {
          code: res.code
        }).then(res => {
          console.log(res, '登录返回');
          app.globalData.token = res.token
          app.globalData.is_new = res.is_new
          // wx.setStorageSync('token', res.token)
          // wx.setStorageSync('is_new', res.is_new)
          if (res.is_new !== 0) {
            request('/api/user/info', res.token).then(res => {
              console.log(res, "config");
              app.globalData.userInfo = res.data
            })
          }
          console.log(res, 'data')
          console.log(res, '登录返回');
          const {
            is_new
          } = res
          this.setData({
            is_new
          })
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading({
      title: '刷新中 ...',
    })
    // 请求登录并请求首页数据
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // console.log(res)
        request('/api/common/login', '', 'get', {
          code: res.code
        }).then(res => {
          console.log(res, '登录返回');
          app.globalData.token = res.token
          app.globalData.is_new = res.is_new
          // wx.setStorageSync('token', res.token)
          // wx.setStorageSync('is_new', res.is_new)
          if (res.is_new !== 0) {
            request('/api/user/info', res.token).then(res => {
              console.log(res, "config");
              app.globalData.userInfo = res.data
            })
          }
          if (res.is_new === 2 && app.globalData.pid) {
            request('/api/user/bindingUser?pid=' + app.globalData.pid, app.globalData.token, 'put', ).then(res => {})
          }
          console.log(res, 'data')
          console.log(res, '登录返回');
          const {
            is_new
          } = res
          this.setData({
            is_new
          })
          this.loadData().then(async res => {
            let {
              banner,
              cate
            } = res.data
            console.log(res.data, 1)
            const requestArr = cate instanceof Array && cate.map((item, index) => {
              return this.product(item.id)
            })
            await Promise.all(requestArr).then(items => {
              console.log(items)

              wx.hideLoading({
                success: (res) => {
                  wx.stopPullDownRefresh()
                },
              })
              const tabs = cate instanceof Array && cate.map((item, index) => {
                item.list = items[index].data
                item.page = 1
                return item
              })
              this.setData({
                banner,
                tabs,
                page: 1
              })
              this.setData({
                activeTab: 0
              })
              this.tabsSwiperHeight();
            })



          })
        }).catch(err => {
          console.log(err, '登录错误');
        })
      }
    })

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: async function () {
    wx.showLoading({
      title: '加载中 ...',
    })
    await this.product(this.data.tabs[this.data.activeTab].id, this.data.page + 1).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.data.length <= 0) {
        wx.showToast({
          title: '已经到底了哦~',
          icon: 'none'
        })
        return
      }
      const tabs = this.data.tabs
      tabs[this.data.activeTab].list = [...tabs[this.data.activeTab].list, ...res.data]
      console.log(tabs, 'tabs');
      this.setData({
        tabs,
        page: this.data.page + 1
      })
    })
    this.tabsSwiperHeight();
    if (res.data.length < 8) {
      wx.showToast({
        title: '已经到底了哦~',
        icon: 'none'
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})